//
//  ViewController.m
//  NZOCJSBridge
//
//  Created by zhao on 15/6/23.
//  Copyright (c) 2015年 nerozhao. All rights reserved.
//

#import "ViewController.h"
#import "NZOCJSBridge.h"

@interface ViewController () 
@property NZOCJSBridge *bridge;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)viewWillAppear:(BOOL)animated {
    if (_bridge) {
        return;
    }
    UIWebView *webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:webView];
    
    [NZOCJSBridge enableLogging];
    __block __typeof(self) wself = self;
    _bridge = [NZOCJSBridge bridgeForWebView:webView webViewDelegate:self handler:^(id data, NZJSResponseCallback responseCallback) {
        NSLog(@"ObjC received message from JS: %@", data);
        [wself pushVC];
        responseCallback(@"Response for message from ObjC:pushvc complete");
    }];
    
//    [_bridge send:@"A string sent from ObjC before Webview has loaded." responseCallback:^(id responseData) {
//        NSLog(@"objc got response! %@", responseData);
//    }];
    
    [self renderButtons:webView];
    [self loadExamplePage:webView];
}

- (void)pushVC{
    UIViewController *vc = [[UIViewController alloc]init];
    vc.view.backgroundColor = [UIColor redColor];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    NSLog(@"webViewDidStartLoad");
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"webViewDidFinishLoad");
}

- (void)renderButtons:(UIWebView*)webView {
    UIFont* font = [UIFont fontWithName:@"HelveticaNeue" size:12.0];
    
    UIButton *messageButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [messageButton setTitle:@"OC Send message to JS" forState:UIControlStateNormal];
    [messageButton addTarget:self action:@selector(sendMessage:) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:messageButton aboveSubview:webView];
    messageButton.frame = CGRectMake(10, 414, 150, 45);
    messageButton.titleLabel.font = font;
    messageButton.backgroundColor = [UIColor colorWithWhite:1 alpha:0.75];
}

- (void)sendMessage:(id)sender {
    [_bridge send:@"OC send String to JS" responseCallback:^(id response) {
        NSLog(@"OC got response: %@", response);
    }];
}

- (void)loadExamplePage:(UIWebView*)webView {
    NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"html"];
    NSString* appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
    NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
    [webView loadHTMLString:appHtml baseURL:baseURL];
}

@end
